const fs = require('fs');
const path = require('path');

// 使用方法:

function toHump(name) {
  return name.replace(/\-(\w)/g, function (_all, letter) {
    return letter.toUpperCase();
  });
}

function walkSync(currentDirPath, callback) {
  fs.readdirSync(currentDirPath, { withFileTypes: true }).forEach(
    function (dirent) {
      const filePath = path.join(currentDirPath, dirent.name);
      if (dirent.isFile()) {
        callback(filePath, dirent);
      } else if (dirent.isDirectory()) {
        walkSync(filePath, callback);
      }
    },
  );
}

let resultStr = '/*运行init.cjs文件生成产物,一般无需改动 生成时间 */\n\n';

let tempStr = 'export const quasarExtras = [\n';
walkSync('node_modules/@quasar/extras', function (filePath) {
  //console.log(filePath);
  if (filePath.indexOf('icons.json') != -1) {
    const aa = filePath;
    let bb = aa.split('\\');
    bb = bb.slice(1, bb.length - 1);

    const formStr = bb.join('/');

    const tempPath = formStr.replaceAll('/', '');

    if (!fs.existsSync('icon_modules/' + tempPath + '/index.mjs')) {
      fs.mkdirSync('icon_modules', { recursive: true });
    }

    fs.copyFileSync(
      'node_modules/' + formStr + '/index.mjs',
      'icon_modules/' + tempPath + '.mjs',
    );

    const importStr = toHump(bb[bb.length - 1]);

    resultStr += `import ${importStr} from '${formStr}/icons.json';\n`;

    tempStr += `{iconTypeName: '${importStr}',fromStr: '${formStr}',iconNames: ${importStr},},\n`;
  }
});
tempStr += '];\n';
resultStr += tempStr;

tempStr = 'export const quasarExtrasSvgIcons = [\n';
walkSync('node_modules/quasar-extras-svg-icons', function (filePath) {
  if (filePath.indexOf('icons.json') != -1) {
    const aa = filePath;
    let bb = aa.split('\\');

    bb = bb.slice(1, bb.length - 1);

    const formStr = bb.join('/');
    const importStr = toHump(bb[bb.length - 1]);

    const tempPath = formStr.replaceAll('/', '');

    if (!fs.existsSync('icon_modules/' + tempPath + '.mjs')) {
      fs.mkdirSync('icon_modules', { recursive: true });
    }

    fs.copyFileSync(
      'node_modules/' + formStr + '/index.mjs',
      'icon_modules/' + tempPath + '.mjs',
    );

    resultStr += `import ${importStr} from '${formStr}/icons.json';\n`;

    tempStr += `{iconTypeName: '${importStr}',fromStr: '${formStr}',iconNames: ${importStr},},\n`;
  }
});
tempStr += '];\n';
resultStr += tempStr;
fs.writeFile('src/IconSet.ts', resultStr, 'utf8', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('文件写入成功！');
  }
});
